//
//  Language.cpp
//  zoudasmallworld
//
//  Created by 周俊 on 14-10-31.
//
//

//文件编码UTF-8
#include "Language.h"

#include <fstream>

#include "Helper.h"

TSP_NS_START

static Language* g_pInstance = nullptr;
const char* Language::FILE_NOT_EXIST = "File not exist";

Language::Language()
    : m_pCurrentTransferor(nullptr)
    , m_currentLanguage(kLangUnknown)
{
}

Language::~Language()
{
    m_currentLanguage = kLangUnknown;
    m_pCurrentTransferor = nullptr;
    for ( auto pair : m_transferors )
    {
        delete pair.second;
    }
    g_pInstance = nullptr;
}

Language* Language::getInstance()
{
    if ( g_pInstance == nullptr )
    {
        g_pInstance = new Language();
    }
    return g_pInstance;
}

int Language::setLanguage(LangName langName)
{
    m_currentLanguage = langName;
    auto it = m_transferors.find(langName);
    if ( it == m_transferors.end() )
    {
        return -1;
    }
    m_pCurrentTransferor = m_transferors[langName];
    return 0;
}

int Language::loadFile(LangName langName, const char* language_file)
{
    std::ifstream language_data;
    language_data.open(language_file);
    if (!language_data.is_open())
    {
        throw FILE_NOT_EXIST;
        return -1;
    }

    //create a new dictionary for transfer language
    auto pHashMap = new std::unordered_map<std::string, std::string>();

    char key[1024];
    char value[1024];

    while (!language_data.eof())
    {
        std::string line;
        getline(language_data, line);
        if (line.length() > 3)
        {
            sscanf(line.c_str(), "%[^=]=%[^=]", key, value);
            (*pHashMap)[key] = value;
        }
    }

    language_data.close();

    //delete old data
    auto it = m_transferors.find(langName);
    if (it != m_transferors.end() )
    {
        delete it->second;
    }

    //save new data
    m_transferors[langName] = pHashMap;
    m_pCurrentTransferor = pHashMap;
    m_currentLanguage = langName;

    return 0;
}

const char* Language::getString(const char* key)
{
    if ( g_pInstance->m_pCurrentTransferor )
    {
        auto iter = g_pInstance->m_pCurrentTransferor->find(key);
        if (iter == g_pInstance->m_pCurrentTransferor->end() )
        {
            return key;
        }
        return iter->second.c_str();
    }
    return key;
}

TSP_NS_END